package instructionSelection.blocks;

import instructionSelection.canolize.StmListList;
import translate.activationRegister.temp.Label;
import treeIR.CJUMP;
import treeIR.JUMP;
import treeIR.LABEL;
import treeIR.Stm;
import treeIR.StmList;

/***/
public class BasicBlocks {
  
	/***/
	public StmListList blocks;
	/***/
	public Label done;
	/***/
	private StmListList lastBlock;
	/***/
	private StmList lastStm;

	/***/
	private void addStm(Stm s) {
		lastStm = (StmList) (lastStm.tail = new StmList(s,null));
	}

	/**
	 * 
	 * 
	 * */
	private void doStms(StmList l) {
		if (l==null) 
			doStms(new StmList(new JUMP(done), null));
		else if (l.head instanceof JUMP || l.head instanceof CJUMP) {
			addStm(l.head);
			mkBlocks((StmList) l.tail);
		} 
		else if (l.head instanceof LABEL)
           doStms(new StmList(new JUMP(((LABEL)l.head).label),l));
		else {
			addStm(l.head);
			doStms((StmList) l.tail);
		}
	}

	/**
	 * 
	 * 
	 * */
	void mkBlocks(StmList l) {
		if (l==null) return;
		else if (l.head instanceof LABEL) {
			lastStm = new StmList(l.head,null);
			if (lastBlock==null)
				lastBlock= blocks= new StmListList(lastStm,null);
			else
				lastBlock = (StmListList) (lastBlock.tail = new StmListList(lastStm,null));
			doStms((StmList) l.tail);
		}
		else mkBlocks(new StmList(new LABEL(new Label()), l));
	}
   
	/**
	 * 
	 * */
	public BasicBlocks(StmList stms) {
    done = new Label();
    mkBlocks(stms);
	}
	
}
